import { useStore } from "@/stores";
import service from "@/service";


// 和风天气查询KEY
const weatherKey = '054a49a8e3fd4dbc9ffe8b0c6945e874';

/**
 * 获取7天内天气预报信息
 * @param {*} location 
 * @returns 
 */
export function get7dWeather(location) {
    return service({
        // url: `https://devapi.qweather.com/v7/weather/7d`,
        url: `https://n45u9tggk9.re.qweatherapi.com/v7/weather/7d`,
        method: 'GET',
        params: {
            key: weatherKey,
            location: location,
        }
    })
}
function getWeatherByLoc(loc) {
    const store = useStore();
    var weekArray = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")
    return new Promise((resolve, reject) => {
        get7dWeather(loc).then(weatherInfo => {
            console.log(weatherInfo);
            if (weatherInfo['code'] == 200) {
                const daily = weatherInfo['daily'];
                daily.forEach(item => {
                    item['week'] = weekArray[new Date(item['fxDate']).getDay()];
                    item['icon-day'] = 'qi-' + item['iconDay'];
                });
                const result = {
                    lastSearchTime: Date.now(),
                    weather: weatherInfo
                }
                store.setWeater(result)
                resolve(result);
            } else {
                reject(weatherInfo)
            }
        })
    });
}

export function getWeatherByCityLoc(loc) {
    const store = useStore();
    const weather = store['weather'];
    const lastSearchTime = weather['lastSearchTime'];
    return new Promise((resolve, reject) => {
        if (weather['weather']) {
            //每隔3个小时查询一次天气
            if (Date.now() - lastSearchTime >= 3 * 60 * 1000 * 1000) {
                getWeatherByLoc(loc).then(res => {
                    resolve(res);
                })
            } else {
                console.log("从缓存中读取天气信息", store['weather']);
                resolve(store['weather']);
            }
        } else {
            getWeatherByLoc(loc).then(res => {
                resolve(res);
            })
        }

    });
}
